package com.wxtt.android.activity;

import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.fast.dev.frame.glide.GlideLoader;
import com.fast.dev.frame.glide.MulBitmapTransformation;
import com.fast.dev.frame.ui.ActivityStack;
import com.fast.dev.frame.ui.Bind;
import com.fast.dev.frame.ui.ContentView;
import com.fast.dev.frame.utils.UIUtils;
import com.three.WeiboUtils;
import com.wxtt.android.R;
import com.wxtt.android.adapter.ViewPageFragmentAdapter;
import com.wxtt.android.bean.UserBean;
import com.wxtt.android.common.CommonActivity;
import com.wxtt.android.config.ApiConfig;
import com.wxtt.android.config.SpConfig;
import com.wxtt.android.fragment.JokeFragment;
import com.wxtt.android.fragment.VideoFragment;
import com.wxtt.android.fragment.WxFragment;
import com.wxtt.android.view.HandlerHelper;
import com.zxing.activity.CaptureActivity;

@ContentView(R.layout.activity_main)
public class MainActivity extends CommonActivity {

    @Bind(id = R.id.tab_main)
    private TabLayout tab_main;
    @Bind(id = R.id.vp_main)
    private ViewPager vp_main;
    @Bind(id = R.id.drawer_navigation)
    private NavigationView drawer_navigation;
    @Bind(id = R.id.drawer_layout)
    private DrawerLayout drawer_layout;

    private ImageView iv_user_head;
    private TextView tv_user_name;

    private Toolbar toolbar;
    private ActionBarDrawerToggle mDrawerToggle;
    private ViewPageFragmentAdapter mAdapter;
    private MulBitmapTransformation headTransformation;
    //延迟跳转时间
    private final int DELAY_SHOW_TIME = 500;

    @Override
    protected boolean showToolbar() {
        return true;
    }

    @Override
    protected void onCustomToolbar(View view, Toolbar toolbar) {
        this.toolbar = toolbar;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    /**
     * 说明：实现菜单和返回键切换
     * @param savedInstanceState
     */
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onInit(Bundle bundle) {
        //初始化侧滑栏
        initDrawer();
        //初始化ViewPager
        initViewPager();
        //初始化其他信息
        initOther();
        //检查更新
        checkUpdate();
    }

    /**
     * 说明：初始化其他信息
     */
    private void initOther(){
        iv_user_head = (ImageView) drawer_navigation.getHeaderView(0).findViewById(R.id.iv_user_head);
        tv_user_name = (TextView) drawer_navigation.getHeaderView(0).findViewById(R.id.tv_user_name);
        headTransformation = new MulBitmapTransformation(this,MulBitmapTransformation.TYPE_CIRCLE);
    }

    /**
     * 说明：设置用户信息
     */
    private void setUserInfo(){
        if (!WeiboUtils.isLoginTimeOut()){
            UserBean bean = SpConfig.getUserBean();
            if (bean == null){
                loginFail();
            }else {
                loginSuccess(bean);
            }
        }else {
            loginFail();
        }
    }

    /**
     * 说明：登录成功
     * @param bean
     */
    private void loginSuccess(UserBean bean){
        SpConfig.setLoginState(true);
        GlideLoader.load(this,bean.getProfile_image_url()).centerCrop().bitmapTransform(headTransformation).into(iv_user_head);
        tv_user_name.setText(bean.getScreen_name());
        iv_user_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showActivity(MainActivity.this,UserCenterActivity.class);
            }
        });
    }

    /**
     * 说明：登录失败
     */
    private void loginFail(){
        SpConfig.setLoginState(false);
        tv_user_name.setText(R.string.user_not_login);
        iv_user_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showActivity(MainActivity.this, LoginActivity.class);
            }
        });
        GlideLoader.load(this, R.drawable.default_user).centerCrop().bitmapTransform(headTransformation).into(iv_user_head);
    }

    /**
     * 说明：检查更新
     */
    private void checkUpdate(){
        ApiConfig.checkUpdate(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置用户信息
        setUserInfo();
    }

    /**
     * 说明：初始化ViewPager
     */
    private void initViewPager() {
        String[] title = UIUtils.getStringArray(R.array.main_tab);
        mAdapter = new ViewPageFragmentAdapter(getSupportFragmentManager(),vp_main,tab_main);
        mAdapter.addTab(title[0], WxFragment.class, null);
        mAdapter.addTab(title[1], VideoFragment.class, null);
        mAdapter.addTab(title[2], JokeFragment.class, null);
    }

//    private Bundle getBundle(String value){
//        Bundle bundle = new Bundle();
//        return null;
//    }

    /**
     * 说明：初始化侧滑栏
     */
    private void initDrawer() {
        mDrawerToggle = new ActionBarDrawerToggle(this,drawer_layout,toolbar,0,0);
        setDrawerContent(drawer_navigation);
        drawer_layout.setDrawerListener(mDrawerToggle);
    }

    /**
     * 说明：设置NavigationView点击事件
     */
    private void setDrawerContent(NavigationView view){
        view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.navigation_item_home:
                        //首页
                        break;
                    case R.id.navigation_item_collect:
                        //我的收藏
                        if (SpConfig.isLogin()){
                            postDelayStart(FavouriteActivity.class);
                        }else {
                            postDelayStart(LoginActivity.class);
                        }
                        break;
                    case R.id.navigation_item_message:
                        //我的消息
                        postDelayStart(MyMessageActivity.class);
                        break;
                    case R.id.navigation_item_suggest:
                        //意见反馈
                        postDelayStart(SuggestActivity.class);
                        break;
                    case R.id.navigation_item_setting:
                        //设置
                        postDelayStart(SettingActivity.class);
                        break;
                    default:
                        break;
                }
                drawer_layout.closeDrawers();
                return true;
            }
        });
    }

    /**
     * 说明：延时跳转
     */
    private void postDelayStart(final Class<?> clazz){
        HandlerHelper.postDelay(DELAY_SHOW_TIME, new Runnable() {
            @Override
            public void run() {
                showActivity(MainActivity.this, clazz);
            }
        });
    }

    private long touchTime = 0;
    private long waitTime = 2000;
    @Override
    public void onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)){
            drawer_layout.closeDrawers();
        }else {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - touchTime) >= waitTime) {
                shortMessage(vp_main,UIUtils.getString(R.string.app_exit));
                touchTime = currentTime;
            }else {
                //退出程序
                showActivity(this, MainActivity.class);
                finish();
                ActivityStack.create().AppExit();
            }
        }
    }

    @Override
    protected int setMenu() {
        return R.menu.main_menu;
    }

    @Override
    protected void onMenuItemClick(int id) {
        switch (id){
//            case R.id.main_meun_find:
//                String url = "https://px-capital.com:443/api/v1/profile";
//                RequestParams params = new RequestParams();
//                params.putHeader("Authorization",token);
//                HttpUtils.get(url, params, new StringHttpCallBack() {
//                    @Override
//                    public void onSuccess(String result) {
//                        shortToast(result);
//                    }
//
//                    @Override
//                    public void onFailure(int errorCode, String msg) {
//                        shortToast(msg + "失败了。。。");
//                    }
//                });
//                showActivity(this, SearchActivity.class);
//                break;
            case R.id.main_meun_sacn:
//                String url1 = "https://px-capital.com:443/api/v1/auth_token";
//                RequestParams params1 = new RequestParams();
//                params1.put("phone","18871584808");
//                params1.put("password","123");
//                HttpUtils.post(url1, params1, new StringHttpCallBack() {
//                    @Override
//                    public void onSuccess(String result) {
//                        try {
//                            JSONObject object = new JSONObject(result);
//                            token = object.optString("token");
//                            shortToast(token);
//                        } catch (Exception e) {
//
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(int errorCode, String msg) {
//                        shortToast(msg + "失败了。。。");
//                    }
//                });
                showActivity(this, CaptureActivity.class);
                break;
            default:
                break;
        }
    }

}
